package util

import (
	"bytes"
	"encoding/json"
	"gitee.com/zenpk/backend-demo/internal/dto"
	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/assert"
	"net/http"
	"net/http/httptest"
	"testing"
)

// LoginAsUser 以 User 的身份登录
func LoginAsUser(t *testing.T, router *gin.Engine, newReq *http.Request) {
	rec := httptest.NewRecorder()
	// 这里给定一个 User 身份的用户数据
	loginReq := dto.LoginReq{
		Email:    "test@test.com",
		Password: "123456",
	}
	loginReqJSON, err := json.Marshal(loginReq)
	assert.NoError(t, err)
	// 执行一次模拟的登录操作
	req, err := http.NewRequest(http.MethodPost, "/user/login", bytes.NewBuffer(loginReqJSON))
	req.Header.Add("Content-Type", "application/json")
	router.ServeHTTP(rec, req)
	// 将 Cookie 写入新的请求
	for _, cookie := range rec.Result().Cookies() {
		newReq.AddCookie(cookie)
	}
}
